package com.baidu.lib_home.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import androidx.appcompat.content.res.AppCompatResources
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.baidu.lib_audio.AudioController
import com.baidu.lib_common.R
import com.baidu.lib_common.animator.rotate
import com.baidu.lib_common.animator.stopRotate
import com.baidu.lib_common.animator.toRotateAngle
import com.baidu.lib_common.base.BaseFragment
import com.baidu.lib_common.constant.AudioChangeEvent
import com.baidu.lib_common.constant.AudioIndexChangeEvent
import com.baidu.lib_common.constant.AudioLoadEvent
import com.baidu.lib_common.constant.AudioOverEvent
import com.baidu.lib_common.constant.AudioPauseEvent
import com.baidu.lib_common.constant.AudioProgressUpdateEvent
import com.baidu.lib_common.constant.AudioStartEvent
import com.baidu.lib_common.utils.loadurl
import com.baidu.lib_home.adapter.BottomViewAdapter
import com.baidu.lib_home.adapter.ViewPagerApapter
import com.baidu.lib_home.databinding.FragmentMainBinding
import com.baidu.lib_home.viewmodel.MainViewModel
import com.baidu.lib_leancloud.LeanCloudManager
import com.baidu.lib_leancloud.model.Music
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class MainFragment : BaseFragment<FragmentMainBinding>() {
    val mainViewModel: MainViewModel by activityViewModels()
    private var isSwitched = false
    private var shouldScrollChangeMusic = true
    private var isScrolling = false
    private var isInit = true
    init {
        EventBus.getDefault().register(this)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun initUI(savedInstanceState: Bundle?) {
        super.initUI(savedInstanceState)
        mBinding.viewPager.isUserInputEnabled = false
        mBinding.viewPager.adapter = ViewPagerApapter(
            listOf(
                HomeFragment(),
                RoamFragment(),
                PersonalFragment()
            ),
            requireActivity()
        )
        val tab0 = mBinding.tabLayout.newTab().setText("推荐").setIcon(AppCompatResources.getDrawable(requireActivity(), R.drawable.tab_home))
        val tab1 = mBinding.tabLayout.newTab().setText("漫游").setIcon(AppCompatResources.getDrawable(requireActivity(), R.drawable.tab_live))
        val tab2 = mBinding.tabLayout.newTab().setText("我的").setIcon(AppCompatResources.getDrawable(requireActivity(), R.drawable.tab_me))
        mBinding.tabLayout.addTab(tab0)
        mBinding.tabLayout.addTab(tab1)
        mBinding.tabLayout.addTab(tab2)
        tab0.view.setOnClickListener{
            mBinding.cardView.visibility = View.VISIBLE
            mBinding.viewPager.setCurrentItem(0,false)
        }
        tab1.view.setOnClickListener{
            mBinding.cardView.visibility = View.GONE
            val randomMusic = LeanCloudManager.instance.getRandomMusic()
            AudioController.instance.changePlayMode(true)
            EventBus.getDefault().post(AudioChangeEvent(randomMusic, listOf(randomMusic)))
            findNavController().navigate(com.baidu.lib_home.R.id.action_mainFragment_to_musicPlayFragment)
        }
        tab2.view.setOnClickListener{
            mBinding.cardView.visibility = View.VISIBLE
            mBinding.viewPager.setCurrentItem(2,false)
        }

        initRecyclerView()
        initEvent()
        mainViewModel.currentMusic.observe(viewLifecycleOwner){music ->
            mBinding.bottomMusicImage.loadurl(music.image,true)
            mBinding.bottomMusicImage.toRotateAngle()
        }


    }

    override fun onResume() {
        super.onResume()
        scrollRecyclerView(AudioController.instance.currentIndex)
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun OnAudioChangeEvent(event: AudioChangeEvent){
        mainViewModel.currentMusic.postValue(event.music)
        mainViewModel.currentChartMusic.postValue(event.musics)
        val index = event.musics.indexOf(event.music)
        scrollRecyclerView(index)
        AudioController.instance.initMusicList(event.musics,index)
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun OnAudioLoadEvent(event: AudioLoadEvent){
        mainViewModel.currentMusic.postValue(event.music)
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun OnAudioIndexChangeEvent(event: AudioIndexChangeEvent){
       scrollRecyclerView(event.index)
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun OnAudioStartEvent(event: AudioStartEvent){
        mBinding.startBtn.setImageResource(R.drawable.audio_stop)
        mBinding.bottomMusicImage.rotate()
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun OnAudioEndEvent(event: AudioPauseEvent){
        mBinding.startBtn.setImageResource(R.drawable.audio_play)
        mBinding.bottomMusicImage.stopRotate()
    }

    override fun onStop() {
        super.onStop()
        mBinding.bottomMusicImage.stopRotate()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
    fun scrollRecyclerView(index: Int){
        shouldScrollChangeMusic = false
        mBinding.recyclerView.scrollToPosition(index)
    }
    fun initRecyclerView(){
        val adapter = BottomViewAdapter()
        mBinding.recyclerView.layoutManager = LinearLayoutManager(
            requireContext(),
            LinearLayoutManager.HORIZONTAL,
            false)
        mBinding.recyclerView.adapter = adapter
        PagerSnapHelper().attachToRecyclerView(mBinding.recyclerView)
        LeanCloudManager.instance.chartMusicModelList.observe(viewLifecycleOwner){
            if(isInit){
                mainViewModel.currentChartMusic.postValue(it[2].music)
                mainViewModel.currentMusic.postValue(it[2].music[0])
                AudioController.instance.initMusicList(it[2].music)

                isInit = false
            }
        }
        if(AudioController.instance.isPlaying()){
            mBinding.startBtn.setImageResource(R.drawable.audio_stop)
            mBinding.bottomMusicImage.rotate()
        }
        mainViewModel.currentChartMusic.observe(viewLifecycleOwner){musicList ->
            adapter.setNewData(musicList)
        }
        mBinding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                //获取当前显示的item
                val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                val position = layoutManager.findFirstVisibleItemPosition()


                if (AudioController.instance.currentIndex == position) return
                if (shouldScrollChangeMusic && !isSwitched) {
                    //通过判断dx的值来切换歌曲
                    //dx > 0：下一曲  dx < 0: 上一曲
                    if (dx > 0) {
                        AudioController.instance.scrollNext()
                        isSwitched = true
                    } else if (dx < -100) {
                        AudioController.instance.scrollPrevious()
                        isSwitched = true
                    }else{
                        isSwitched = false
                        AudioController.instance.scrollPrevious()
                        AudioController.instance.scrollNext()
                    }

                }else{
                    shouldScrollChangeMusic = true
                }
            }
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                when (newState) {
                    // 1. 滑动开始前（手指刚接触并准备拖动）
                    RecyclerView.SCROLL_STATE_DRAGGING -> {
                        if (!isScrolling) { // 防止重复触发
                            isSwitched = false // 滑动开始前重置
                            isScrolling = true
                        }
                    }
                    // 2. 滑动结束后（完全停止）
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        isSwitched = false // 滑动结束后重置
                        isScrolling = false
                    }
                    // 3. 惯性滑动中（手指已离开，但列表还在动）
                    RecyclerView.SCROLL_STATE_SETTLING -> {
                        // 无需重置，保持标记状态直到滑动结束

                    }
                }
            }
        })
    }
    fun initEvent(){
        mBinding.cardView.setOnClickListener{
            findNavController().navigate(com.baidu.lib_home.R.id.action_mainFragment_to_musicPlayFragment)
        }
        mBinding.playList.setOnClickListener{
            findNavController().navigate(com.baidu.lib_home.R.id.action_mainFragment_to_musicListFragment)
        }
        mBinding.startBtn.setOnClickListener{
            AudioController.instance.startOrPause()
        }
    }

}